<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ disabled: disableSubmit }"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 采购明细 -->
        <div class="table-operator" style="margin-bottom: 10px">
          <a-button type="primary" icon="import" @click="handleImportMaterial">批量选择物料</a-button>
        </div>

        <a-table
          ref="detailTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="detailColumns"
          :dataSource="detailList"
          :pagination="false"
          :scroll="{ x: 1200 }"
        >
          <!-- 物料选择 -->
          <template slot="materialSlot" slot-scope="text">
            <span>{{ text || '-' }}</span>
          </template>

          <!-- 物料名称 -->
          <template slot="materialNameSlot" slot-scope="text">
            <span>{{ text || '-' }}</span>
          </template>

          <!-- 物料图片 -->
          <template slot="materialImageSlot" slot-scope="text, record">
            <div v-if="record.materialImage" class="material-thumbnail-container">
              <a-carousel dots-position="bottom" arrows autoplay>
                <div
                  v-for="(img, index) in getImagesArray(record.materialImage)"
                  :key="index"
                  class="material-image-item"
                >
                  <img
                    :src="getImageUrl(img)"
                    class="material-thumbnail"
                    alt="物料图片"
                    @click="handlePreviewImage(img)"
                    @error="handleImageError"
                  />
                </div>
              </a-carousel>
            </div>
            <span v-else>-</span>
          </template>

          <!-- 物料类型 -->
          <template slot="materialTypeSlot" slot-scope="text">
            <a-tag
              :color="
                text == '1'
                  ? 'blue'
                  : text == '2'
                  ? 'green'
                  : text == '3'
                  ? 'orange'
                  : text == '4'
                  ? 'purple'
                  : text == '5'
                  ? 'red'
                  : text == '6'
                  ? 'yellow'
                  : ''
              "
            >
              {{
                text == '1'
                  ? '型材'
                  : text == '2'
                  ? '配件'
                  : text == '3'
                  ? '辅件'
                  : text == '4'
                  ? '其他'
                  : text == '5'
                  ? '余料'
                  : text == '6'
                  ? '半料'
                  : '-'
              }}
            </a-tag>
          </template>

          <!-- 规格型号 -->
          <template slot="specificationSlot" slot-scope="text">
            <span>{{ text || '-' }}</span>
          </template>

          <!-- 供应商选择 -->
          <template slot="supplierSlot" slot-scope="text, record, index">
            <a-form-item
              :required="true"
              :validateStatus="record.supplier ? 'success' : 'error'"
              :help="record.supplier ? '' : '请选择供应商'"
              style="margin-bottom: 0"
            >
              <j-select-supplier-modal
                v-model="record.supplier"
                :materialCode="record.materialCode"
                placeholder="请选择供应商"
                @change="(val, supplier) => handleDetailSupplierChange(val, supplier, index)"
              />
            </a-form-item>
          </template>

          <!-- 数量输入 -->
          <template slot="quantitySlot" slot-scope="text, record, index">
            <a-form-item
              :required="true"
              :validateStatus="record.quantity && record.quantity > 0 ? 'success' : 'error'"
              :help="record.quantity && record.quantity > 0 ? '' : '请输入数量'"
              style="margin-bottom: 0"
            >
              <a-input-number
                v-model="record.quantity"
                :min="record.minOrderQuantity || 0.01"
                :precision="2"
                :step="1"
                style="width: 100%"
                placeholder="数量"
                @change="() => handleCalcAmount(index)"
              />
            </a-form-item>
          </template>

          <!-- 单价输入 -->
          <template slot="unitPriceSlot" slot-scope="text, record, index">
            <a-form-item
              :required="true"
              :validateStatus="record.unitPrice && record.unitPrice > 0 ? 'success' : 'error'"
              :help="record.unitPrice && record.unitPrice > 0 ? '' : '请输入单价'"
              style="margin-bottom: 0"
            >
              <a-input-number
                v-model="record.unitPrice"
                :min="0.01"
                :precision="2"
                :step="0.1"
                style="width: 100%"
                placeholder="单价"
                @change="() => handleCalcAmount(index)"
              />
            </a-form-item>
          </template>

          <!-- 交货周期 -->
          <template slot="leadTimeSlot" slot-scope="text">
            <span>{{ text ? text + '天' : '-' }}</span>
          </template>

          <!-- 金额显示 -->
          <template slot="amountSlot" slot-scope="text, record">
            {{ record.amount ? '¥' + parseFloat(record.amount).toFixed(2) : '¥0.00' }}
          </template>

          <!-- 操作列 -->
          <template slot="operation" slot-scope="text, record, index">
            <a-button type="danger" size="small" @click="handleRemoveDetail(index)">删除</a-button>
          </template>
        </a-table>

        <div style="text-align: right; margin-top: 12px">
          <span style="margin-right: 12px"
            >总金额: <b style="color: #f5222d; font-size: 16px">¥{{ totalAmount.toFixed(2) }}</b></span
          >
        </div>

        <!-- 预计到货日期 -->
        <div style="margin-top: 16px">
          <a-form-item label="预计到货日期" :labelCol="{ span: 3 }" :wrapperCol="{ span: 8 }">
            <a-date-picker
              style="width: 100%"
              v-decorator="['expectedArrivalDate', validatorRules.expectedArrivalDate]"
              placeholder="请选择预计到货日期"
              format="YYYY-MM-DD"
            />
          </a-form-item>
        </div>

        <!-- 备注 -->
        <div>
          <a-form-item label="备注" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
            <a-textarea v-decorator="['remark']" :rows="2" placeholder="请输入备注" />
          </a-form-item>
        </div>
      </a-form>
    </a-spin>

    <!-- 批量选择物料弹窗 -->
    <a-modal
      title="批量选择物料"
      :width="1000"
      :visible="materialSelectVisible"
      @ok="handleMaterialSelectOk"
      @cancel="handleMaterialSelectCancel"
      cancelText="取消"
      okText="确定"
    >
      <div class="material-select-container">
        <!-- 搜索区域 -->
        <div class="search-area" style="margin-bottom: 16px">
          <a-row :gutter="24">
            <a-col :span="5">
              <a-input placeholder="物料编号" v-model="materialQueryParam.materialCode" allowClear />
            </a-col>
            <a-col :span="5">
              <a-input placeholder="物料名称" v-model="materialQueryParam.materialName" allowClear />
            </a-col>
            <a-col :span="4">
              <a-select placeholder="物料类型" v-model="materialQueryParam.materialType" allowClear>
                <a-select-option :value="null">全部</a-select-option>
                <a-select-option :value="1">型材</a-select-option>
                <a-select-option :value="2">配件</a-select-option>
                <a-select-option :value="3">辅件</a-select-option>
                <a-select-option :value="4">其他</a-select-option>
                <a-select-option :value="5">余料</a-select-option>
                <a-select-option :value="6">半料</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="10" style="text-align: right">
              <a-button type="primary" @click="searchMaterials" icon="search" style="margin-right: 8px">查询</a-button>
              <a-button @click="resetMaterialSearch" icon="reload" style="margin-right: 8px">重置</a-button>
              <a-dropdown>
                <a-button type="primary" icon="plus"> 新增物料 <a-icon type="down" /> </a-button>
                <a-menu slot="overlay">
                  <a-menu-item key="1" @click="showMaterialModal('1')"> <a-icon type="plus" />添加型材 </a-menu-item>
                  <a-menu-item key="2" @click="showMaterialModal('2')"> <a-icon type="plus" />添加配件 </a-menu-item>
                  <a-menu-item key="3" @click="showMaterialModal('3')"> <a-icon type="plus" />添加辅件 </a-menu-item>
                  <a-menu-item key="4" @click="showMaterialModal('4')"> <a-icon type="plus" />添加其他 </a-menu-item>
                  <a-menu-item key="5" @click="showMaterialModal('5')"> <a-icon type="plus" />添加余料 </a-menu-item>
                  <a-menu-item key="6" @click="showMaterialModal('6')"> <a-icon type="plus" />添加半料 </a-menu-item>
                </a-menu>
              </a-dropdown>
            </a-col>
          </a-row>
        </div>

        <!-- 物料表格 -->
        <a-table
          ref="materialTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="materialColumns"
          :dataSource="materialDataSource"
          :pagination="materialPagination"
          :loading="materialLoading"
          :rowSelection="{ selectedRowKeys: selectedMaterialKeys, onChange: onMaterialSelectChange, type: 'checkbox' }"
          @change="handleMaterialTableChange"
        >
          <template slot="materialImageSlot" slot-scope="text">
            <div v-if="text" class="material-thumbnail-container">
              <a-carousel dots-position="bottom" arrows autoplay>
                <div v-for="(img, index) in getImagesArray(text)" :key="index" class="material-image-item">
                  <img
                    :src="getImageUrl(img)"
                    class="material-thumbnail"
                    alt="物料图片"
                    @click="handlePreviewImage(img)"
                    @error="handleImageError"
                  />
                </div>
              </a-carousel>
            </div>
            <span v-else>-</span>
          </template>

          <template slot="materialTypeSlot" slot-scope="text">
            <a-tag
              :color="
                text == 1 || text == '1'
                  ? 'blue'
                  : text == 2 || text == '2'
                  ? 'green'
                  : text == 3 || text == '3'
                  ? 'orange'
                  : text == 4 || text == '4'
                  ? 'purple'
                  : text == 5 || text == '5'
                  ? 'red'
                  : text == 6 || text == '6'
                  ? 'yellow'
                  : ''
              "
            >
              {{
                text == 1 || text == '1'
                  ? '型材'
                  : text == 2 || text == '2'
                  ? '配件'
                  : text == 3 || text == '3'
                  ? '辅件'
                  : text == 4 || text == '4'
                  ? '其他'
                  : text == 5 || text == '5'
                  ? '余料'
                  : text == 6 || text == '6'
                  ? '半料'
                  : '-'
              }}
            </a-tag>
          </template>

          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="text == '0' ? 'green' : 'red'">
              {{ text == '0' ? '启用' : '禁用' }}
            </a-tag>
          </template>
        </a-table>
      </div>
    </a-modal>

    <!-- 图片预览模态框 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="物料图片" style="width: 100%" :src="previewImage" />
    </a-modal>

    <!-- 型材模态框 -->
    <profile-modal
      ref="profileModal"
      :visible="profileModalVisible"
      @cancel="profileModalVisible = false"
      @ok="handleMaterialAdded"
    />

    <!-- 配件模态框 -->
    <fitting-modal
      ref="fittingModal"
      :visible="fittingModalVisible"
      @cancel="fittingModalVisible = false"
      @ok="handleMaterialAdded"
    />

    <!-- 辅件模态框 -->
    <auxiliary-modal
      ref="auxiliaryModal"
      :visible="auxiliaryModalVisible"
      @cancel="auxiliaryModalVisible = false"
      @ok="handleMaterialAdded"
    />

    <!-- 其他模态框 -->
    <other-modal
      ref="otherModal"
      :visible="otherModalVisible"
      @cancel="otherModalVisible = false"
      @ok="handleMaterialAdded"
    />

    <!-- 余料模态框 -->
    <surplus-modal
      ref="surplusModal"
      :visible="surplusModalVisible"
      @cancel="surplusModalVisible = false"
      @ok="handleMaterialAdded"
    />
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
import JSelectSupplierModal from '@/components/jeecgbiz/JSelectSupplierModal'
import { v4 as uuidv4 } from 'uuid'
import moment from 'moment'
import { getFileAccessHttpUrl } from '@/api/manage'
import ProfileModal from '@/views/wms/material/modules/ProfileModal'
import FittingModal from '@/views/wms/material/modules/FittingModal'
import AuxiliaryModal from '@/views/wms/material/modules/AuxiliaryModal'
import OtherModal from '@/views/wms/material/modules/OtherModal'
import SurplusModal from '@/views/wms/material/modules/SurplusModal'

export default {
  name: 'PurchaseOrderModal',
  components: {
    JSelectMaterial,
    JSelectSupplierModal,
    ProfileModal,
    FittingModal,
    AuxiliaryModal,
    OtherModal,
    SurplusModal,
  },
  data() {
    return {
      title: '新增采购单',
      visible: false,
      materialSelectVisible: false,
      model: {},
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      confirmLoading: false,
      disableSubmit: false,
      form: this.$form.createForm(this),
      validatorRules: {
        expectedArrivalDate: { rules: [{ required: true, message: '请选择预计到货日期!' }] },
      },
      // 各物料模态框可见性控制
      profileModalVisible: false,
      fittingModalVisible: false,
      auxiliaryModalVisible: false,
      otherModalVisible: false,
      surplusModalVisible: false,
      detailColumns: [
        {
          title: '物料编号',
          dataIndex: 'materialCode',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'materialSlot' },
        },
        {
          title: '物料名称',
          dataIndex: 'materialName',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'materialNameSlot' },
        },
        {
          title: '物料图片',
          dataIndex: 'materialImage',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'materialImageSlot' },
        },
        {
          title: '物料类型',
          dataIndex: 'materialType',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'materialTypeSlot' },
        },
        {
          title: '规格型号',
          dataIndex: 'specification',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'specificationSlot' },
        },
        {
          title: '供应商',
          dataIndex: 'supplier',
          width: '20%',
          align: 'center',
          scopedSlots: { customRender: 'supplierSlot' },
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'quantitySlot' },
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: '8%',
          align: 'center',
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'unitPriceSlot' },
        },
        {
          title: '交货周期',
          dataIndex: 'leadTime',
          width: '8%',
          align: 'center',
          scopedSlots: { customRender: 'leadTimeSlot' },
        },
        {
          title: '金额',
          dataIndex: 'amount',
          width: '10%',
          align: 'center',
          scopedSlots: { customRender: 'amountSlot' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '8%',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      detailList: [],
      warningIds: [], // 存储物料预警ID，用于保存后标记已处理
      url: {
        add: '/wms/purchase/add',
        edit: '/wms/purchase/edit',
        queryById: '/wms/purchase/queryById',
        detailList: '/wms/purchase/detail/list',
        materialList: '/wms/material/list',
        markHandled: '/wms/purchase/warning/markHandled', // 标记物料预警已处理
        supplierList: '/wms/supplier/list',
        materialSuppliers: '/wms/supplier/material/suppliers',
      },

      // 图片预览相关
      previewVisible: false,
      previewImage: '',

      // 物料选择相关
      materialQueryParam: {
        materialCode: '',
        materialName: '',
        status: '0', // 默认只查询启用状态的物料
        materialType: null, // 物料类型，null为全部
      },
      materialColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料编号',
          align: 'center',
          dataIndex: 'materialCode',
          width: 120,
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName',
          width: 150,
        },
        {
          title: '物料图片',
          align: 'center',
          dataIndex: 'materialImage',
          width: 80,
          scopedSlots: { customRender: 'materialImageSlot' },
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType',
          width: 80,
          scopedSlots: { customRender: 'materialTypeSlot' },
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
          width: 60,
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 60,
          scopedSlots: { customRender: 'statusSlot' },
        },
      ],
      materialDataSource: [],
      materialLoading: false,
      selectedMaterialKeys: [],
      selectedMaterials: [],
      materialPagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },

      // 以下是为了兼容JeecgListMixin
      selectedRowKeys: [],
      selectionRows: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
    }
  },
  computed: {
    totalAmount() {
      return this.detailList.reduce((sum, item) => {
        return sum + (item.amount || 0)
      }, 0)
    },
  },
  methods: {
    // 以下是为了兼容JeecgListMixin
    loadData() {
      // 空实现，不需要加载数据
    },
    getQueryParams() {
      // 空实现，不需要查询参数
      return {}
    },
    getQueryField() {
      // 空实现，不需要查询字段
      return 'id'
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },

    // 以下是组件自身的方法
    show(record, warningIds) {
      this.visible = true
      this.detailList = []
      this.warningIds = warningIds || [] // 保存物料预警ID

      if (record && !warningIds) {
        // 编辑模式
        this.model = Object.assign({}, record)
        this.title = '编辑采购单'

        this.$nextTick(() => {
          this.form.setFieldsValue({
            expectedArrivalDate: record.expectedArrivalDate ? moment(record.expectedArrivalDate) : null,
            remark: record.remark,
          })

          // 加载采购单明细
          this.loadDetailList(record.id)
        })
      } else {
        // 新增模式
        this.model = {}
        this.title = warningIds ? '基于物料预警生成采购单' : '新增采购单'

        this.$nextTick(() => {
          this.form.resetFields()

          // 如果传入了物料预警ID，则加载对应的物料信息
          if (warningIds && warningIds.length > 0) {
            this.loadMaterialsByWarningIds(warningIds)
          }
        })
      }
    },
    handleAddDetail() {
      this.detailList.push({
        id: uuidv4(),
        materialCode: '',
        materialName: '',
        materialType: '',
        materialImage: '',
        specification: '',
        supplier: '',
        supplierName: '',
        unit: '',
        quantity: 1,
        unitPrice: 0,
        leadTime: null,
        minOrderQuantity: 0.01,
        amount: 0,
        loading: false,
      })
    },

    // 加载采购单明细
    loadDetailList(purchaseOrderId) {
      this.confirmLoading = true
      getAction(this.url.queryDetailList, { purchaseOrderId })
        .then((res) => {
          if (res.success) {
            // 确保加载的明细数据包含materialId字段
            this.detailList = (res.result || []).map((detail) => ({
              ...detail,
              materialId: detail.materialId || '', // 确保包含materialId
              loading: false,
            }))
          } else {
            this.$message.error(res.message || '加载采购单明细失败')
          }
          this.confirmLoading = false
        })
        .catch(() => {
          this.confirmLoading = false
        })
    },

    // 根据物料预警ID加载物料信息
    loadMaterialsByWarningIds(warningIds) {
      this.confirmLoading = true
      postAction('/wms/purchase/warning/getByIds', { ids: warningIds.join(',') })
        .then((res) => {
          if (res.success && res.result && res.result.length > 0) {
            // 将物料信息添加到采购明细列表
            res.result.forEach((warning) => {
              // 计算推荐采购数量
              let recommendedQuantity = 1

              if (warning.suggestedPurchaseQuantity && warning.suggestedPurchaseQuantity > 0) {
                // 如果有建议采购量，直接使用
                recommendedQuantity = parseFloat(warning.suggestedPurchaseQuantity)
              } else if (warning.warningType === 1 && warning.upperLimit && warning.currentQuantity) {
                // 如果是低于下限预警，计算到达上限所需数量
                recommendedQuantity = Math.max(1, parseFloat(warning.upperLimit) - parseFloat(warning.currentQuantity))
              } else if (warning.lowerLimit && warning.currentQuantity) {
                // 其他情况，计算到达下限所需数量
                recommendedQuantity = Math.max(1, parseFloat(warning.lowerLimit) - parseFloat(warning.currentQuantity))
              }
              this.detailList.push({
                materialId: warning.materialId,
                materialCode: warning.materialCode,
                materialName: warning.materialName,
                materialType: warning.materialType || '4',
                materialImage: warning.materialImage,
                specification: warning.specification,
                unit: warning.unit,
                quantity: recommendedQuantity, // 使用计算出的推荐采购数量
                unitPrice: warning.lastPurchasePrice || 0, // 使用最近采购价格作为默认单价
                leadTime: null,
                minOrderQuantity: 0.01,
                amount: 0,
                supplier: warning.commonSupplier || '', // 使用常用供应商作为默认供应商
                supplierName: warning.commonSupplier || '',
                loading: false,
              })
            })
            this.$message.success(`已加载 ${res.result.length} 个物料到采购明细`)
          } else {
            this.$message.warning('未找到相关物料信息')
          }
          this.confirmLoading = false
        })
        .catch(() => {
          this.$message.error('加载物料信息失败')
          this.confirmLoading = false
        })
    },
    handleOk() {
      // 表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          // 明细验证
          if (this.detailList.length == 0) {
            this.$message.warning('请添加采购明细!')
            return
          }

          for (let i = 0; i < this.detailList.length; i++) {
            const detail = this.detailList[i]
            if (!detail.materialCode) {
              this.$message.warning(`第 ${i + 1} 行物料不能为空!`)
              return
            }
            if (!detail.supplier) {
              this.$message.warning(`第 ${i + 1} 行供应商不能为空!`)
              return
            }
            if (!detail.quantity || detail.quantity <= 0) {
              this.$message.warning(`第 ${i + 1} 行数量必须大于0!`)
              return
            }
            if (!detail.unitPrice || detail.unitPrice <= 0) {
              this.$message.warning(`第 ${i + 1} 行单价必须大于0!`)
              return
            }
          }

          // 组装提交数据
          const formData = Object.assign({}, this.model, values)
          if (formData.expectedArrivalDate) {
            formData.expectedArrivalDate = formData.expectedArrivalDate.format('YYYY-MM-DD')
          }
          formData.totalAmount = this.totalAmount

          // 处理明细数据，移除前端临时属性
          const detailListToSubmit = this.detailList.map((item) => {
            // 创建一个新对象，只包含需要提交的字段
            return {
              materialId: item.materialId, // 添加物料ID字段
              materialCode: item.materialCode,
              materialName: item.materialName,
              materialType: item.materialType,
              materialImage: item.materialImage, // 添加物料图片
              specification: item.specification,
              unit: item.unit,
              quantity: item.quantity,
              unitPrice: item.unitPrice,
              leadTime: item.leadTime,
              minOrderQuantity: item.minOrderQuantity,
              amount: item.amount,
              supplier: item.supplier,
              supplierName: item.supplierName,
              supplierId: item.supplierId,
            }
          })

          formData.detailList = detailListToSubmit

          this.confirmLoading = true
          const httpAction = this.model.id ? postAction(this.url.edit, formData) : postAction(this.url.add, formData)
          httpAction
            .then((res) => {
              console.log('res................................', res)
              if (res.success) {
                this.$message.success(res.message || (this.model.id ? '编辑成功!' : '新增成功!'))

                // 如果是基于物料预警创建的采购单，自动标记相关预警为已处理
                console.log('this.model.id................................', this.model.id)
                console.log('this.warningIds................................', this.warningIds)
                console.log('this.warningIds.length................................', this.warningIds.length)
                if (!this.model.id && this.warningIds && this.warningIds.length > 0) {
                  this.markWarningsAsHandled()
                }

                this.handleCancel()
                this.$emit('ok')
              } else {
                this.$message.error(res.message || (this.model.id ? '编辑失败!' : '新增失败!'))
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.disableSubmit = false
      this.model = {}
      this.detailList = []
      this.warningIds = [] // 清空物料预警ID
      this.form.resetFields()
    },

    // 标记物料预警为已处理
    markWarningsAsHandled() {
      if (!this.warningIds || this.warningIds.length === 0) {
        return
      }

      // 批量标记所有相关的物料预警为已处理
      const promises = this.warningIds.map((id) => {
        return postAction(`${this.url.markHandled}?id=${id}`)
      })

      Promise.all(promises)
        .then((results) => {
          const successCount = results.filter((res) => res.success).length
          if (successCount > 0) {
            this.$message.success(`已自动标记 ${successCount} 个物料预警为已处理`)
          }
          if (successCount < results.length) {
            this.$message.warning(`有 ${results.length - successCount} 个物料预警标记失败`)
          }
        })
        .catch((error) => {
          console.error('标记物料预警失败:', error)
          this.$message.error('标记物料预警失败')
        })
    },
    handleRemoveDetail(index) {
      this.detailList.splice(index, 1)
    },
    handleMaterialChange(value, index) {
      if (!value) return

      // 获取物料信息
      getAction(this.url.materialList, { materialCode: value }).then((res) => {
        if (res.success && res.result && res.result.records && res.result.records.length > 0) {
          const material = res.result.records[0]
          this.$set(this.detailList, index, {
            ...this.detailList[index],
            materialId: material.id, // 保存物料ID
            materialCode: material.materialCode,
            materialName: material.materialName,
            materialType: material.materialType,
            materialImage: material.materialImage,
            specification: material.specification,
            unit: material.unit,
            unitPrice: 0,
            supplier: '',
            supplierName: '',
          })

          // 不需要手动加载供应商列表，由JSelectSupplierModal组件处理
          this.$set(this.detailList[index], 'loading', false)
        }
      })
    },

    // 处理明细行供应商变更
    handleDetailSupplierChange(supplierId, supplier, index) {
      if (!supplier) return

      const detail = this.detailList[index]

      // 更新供应商相关信息
      this.$set(detail, 'supplier', supplierId)
      this.$set(detail, 'supplierName', supplier.supplierName)
      this.$set(detail, 'unitPrice', supplier.price || 0)
      this.$set(detail, 'leadTime', supplier.leadTime)
      this.$set(detail, 'minOrderQuantity', supplier.minOrderQuantity || 0.01)
      this.$set(detail, 'supplierId', supplier.id)

      // 如果供应商提供了单位信息，优先使用供应商的单位
      if (supplier.unit) {
        this.$set(detail, 'unit', supplier.unit)
      }

      // 如果有最小订货量，更新数量
      if (supplier.minOrderQuantity && supplier.minOrderQuantity > detail.quantity) {
        this.$set(detail, 'quantity', supplier.minOrderQuantity)
      }

      // 计算金额
      this.handleCalcAmount(index)
    },

    // 计算金额
    handleCalcAmount(index) {
      const detail = this.detailList[index]
      if (detail.quantity && detail.unitPrice) {
        // 计算金额并保留两位小数
        const amount = parseFloat((detail.quantity * detail.unitPrice).toFixed(2))
        this.$set(detail, 'amount', amount)
      } else {
        this.$set(detail, 'amount', 0)
      }

      // 更新总金额（通过计算属性自动更新）
    },

    handleImportMaterial() {
      this.materialSelectVisible = true
      this.selectedMaterialKeys = []
      this.selectedMaterials = []
      this.searchMaterials()
    },

    // 物料查询方法
    searchMaterials() {
      this.materialPagination.current = 1
      this.loadMaterialData()
    },

    // 重置物料查询
    resetMaterialSearch() {
      this.materialQueryParam = {
        materialCode: '',
        materialName: '',
        status: '0',
        materialType: null,
      }
      this.searchMaterials()
    },

    // 加载物料数据
    loadMaterialData() {
      this.materialLoading = true

      const params = {
        pageNo: this.materialPagination.current,
        pageSize: this.materialPagination.pageSize,
        ...this.materialQueryParam,
      }

      // 确保materialType参数有效
      if (params.materialType == '') {
        delete params.materialType
      }

      getAction(this.url.materialList, params)
        .then((res) => {
          if (res.success) {
            this.materialDataSource = res.result.records || []
            this.materialPagination.total = res.result.total || 0
          } else {
            this.$message.error(res.message || '获取物料数据失败')
          }
          this.materialLoading = false
        })
        .catch(() => {
          this.materialLoading = false
          this.$message.error('获取物料数据失败')
        })
    },

    // 物料表格分页变化
    handleMaterialTableChange(pagination, filters, sorter) {
      this.materialPagination.current = pagination.current
      this.materialPagination.pageSize = pagination.pageSize
      this.loadMaterialData()
    },

    // 物料选择变化
    onMaterialSelectChange(selectedRowKeys, selectedRows) {
      this.selectedMaterialKeys = selectedRowKeys
      this.selectedMaterials = selectedRows
    },

    // 处理物料选择确认
    handleMaterialSelectOk() {
      if (!this.selectedMaterials || this.selectedMaterials.length == 0) {
        this.$message.warning('请至少选择一个物料!')
        return
      }

      // 批量添加物料到明细列表
      this.selectedMaterials.forEach((material) => {
        this.detailList.push({
          // 移除前端生成的ID，由后端MyBatisPlus自动生成
          materialId: material.id, // 添加物料ID
          materialCode: material.materialCode,
          materialName: material.materialName,
          materialType: material.materialType || '4', // 默认为其他物料类型
          materialImage: material.materialImage,
          specification: material.specification,
          unit: material.unit,
          quantity: 1,
          unitPrice: 0,
          leadTime: null,
          minOrderQuantity: 0.01,
          amount: 0,
          supplier: '',
          supplierName: '',
          loading: false,
        })
      })

      this.materialSelectVisible = false
      this.$message.success(`已添加 ${this.selectedMaterials.length} 个物料到采购明细`)
    },

    handleMaterialSelectCancel() {
      this.materialSelectVisible = false
    },

    // 图片相关方法
    getImageUrl(text) {
      if (!text) return ''
      try {
        return getFileAccessHttpUrl(text)
      } catch (error) {
        console.error('获取文件URL失败:', error)
        return ''
      }
    },
    handlePreviewImage(text) {
      this.previewImage = this.getImageUrl(text)
      this.previewVisible = true
    },
    handleImageError(e) {
      console.error('图片加载失败:', e)
      e.target.src =
        ''
      e.target.alt = '图片加载失败'
    },

    // 将图片字符串转换为数组
    getImagesArray(text) {
      if (!text) return []
      return text.split(',').filter(Boolean)
    },

    // 添加新增方法，供父组件调用
    add() {
      this.visible = true
      this.model = {}
      this.detailList = []
      this.title = '新增采购单'

      this.$nextTick(() => {
        this.form.resetFields()
      })
    },

    // 添加编辑方法，供父组件调用
    edit(record) {
      if (record) {
        this.show(record)
      } else {
        this.$message.warning('未找到要编辑的记录')
      }
    },

    // 新增物料模态框
    showMaterialModal(type) {
      // 暂时隐藏物料选择弹窗
      this.materialSelectVisible = false

      // 根据物料类型显示对应的模态框
      switch (type) {
        case '1': // 型材
          this.$refs.profileModal.add()
          break
        case '2': // 配件
          this.$refs.fittingModal.add()
          break
        case '3': // 辅件
          this.$refs.auxiliaryModal.add()
          break
        case '4': // 其他
          this.$refs.otherModal.add()
          break
        case '5': // 余料
          this.$refs.surplusModal.add()
          break
        case '6': // 半料
          this.$refs.auxiliaryModal.add() // 半料实际上是辅件的一种，所以使用辅件模态框
          break
      }

      // 确保模态框显示
      this.$nextTick(() => {
        console.log('打开物料模态框类型:', type)
      })
    },

    // 物料添加成功后的回调
    handleMaterialAdded() {
      // 重新打开物料选择弹窗
      this.materialSelectVisible = true
      // 刷新物料列表
      this.searchMaterials()
    },
  },
}
</script>

<style scoped>
.table-operator {
  margin-bottom: 18px;
}

.material-images-container {
  width: 80px;
  margin: 0 auto;
}

.material-image-item {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.material-image {
  max-width: 80px;
  max-height: 60px;
  cursor: pointer;
}

.material-thumbnail-container {
  width: 80px;
  height: 60px;
  margin: 0 auto;
  overflow: hidden;
}

.material-thumbnail {
  max-width: 80px;
  max-height: 60px;
  cursor: pointer;
  object-fit: contain;
}

/* 自定义轮播图样式 */
.material-thumbnail-container .ant-carousel {
  height: 100%;
}

.material-thumbnail-container .ant-carousel .slick-slide {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.material-thumbnail-container .ant-carousel .slick-dots {
  margin: 0;
  padding: 0;
  height: 12px;
  bottom: 0;
}

.material-thumbnail-container .ant-carousel .slick-dots li button {
  width: 6px;
  height: 6px;
}

/* 表格样式优化 */
::v-deep .ant-table-tbody > tr > td {
  padding: 8px;
  vertical-align: middle;
}

::v-deep .ant-table-thead > tr > th {
  padding: 10px 8px;
  background-color: #fafafa;
}

::v-deep .ant-form-item {
  margin-bottom: 0;
}

::v-deep .ant-table-bordered .ant-table-thead > tr > th,
::v-deep .ant-table-bordered .ant-table-tbody > tr > td {
  border-right: 1px solid #e8e8e8;
}
</style> 